package com.guw.AWT;

import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

//简易计算器,这个方法更加面向对象,采用的是组合法而非继承
public class TestCalc2 {
    public static void main(String[] args) {
        new Calculator2().loadFrame();
    }
}

//计算器类
class Calculator2 extends Frame{
    //属性
    TextField num1,num2,num3;
    //方法
    public void loadFrame(){
        num1 = new TextField(10);
        num2 = new TextField(10);
        num3 = new TextField(20);
        //1个按钮
        Button button = new Button("=");
        //1个标签
        Label label = new Label("+");
        //绑定监听事件,在此处使用了组合,以便使用MyCalculatorListener2中的方法
        button.addActionListener(new MyCalculatorListener2(this));

        //布局:流式布局
        setLayout(new FlowLayout());
        add(num1);
        add(label);
        add(num2);
        add(button);
        add(num3);

        pack();
        setVisible(true);
    }
}

//监听器类
class MyCalculatorListener2 implements ActionListener{
    //获取计算器这个对象
    Calculator2 calculator2 = null;
    //构造方法
    public MyCalculatorListener2(Calculator2 calculator2){
        this.calculator2 = calculator2;
    }

    @Override
    public void actionPerformed(ActionEvent e) {
        //获得加数和被加数
        int n1 = Integer.parseInt(calculator2.num1.getText());
        //将这两个值+运算之后,放到第三个框
        int n2 = Integer.parseInt(calculator2.num2.getText());
        calculator2.num3.setText(""+(n1+n2));
        //清除前两个框的数值
        calculator2.num1.setText("");
        calculator2.num2.setText("");

    }
}
